/*
Copyright 2010 Dmitry Barashev

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
package net.barashev.seclub.io;

import index.CalculatorOfWorkingWithDisk;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.WritableByteChannel;

/**
 * A slot for appending to a persistent data storage. It can only append values.
 * It flushes automatically once it is full, but it is writer's responsibility to
 * flush and release this slot at the end.
 * @author Dmitry Barashev
 */
public class OutputSlot<T, M extends DataMarshaller<T>> implements Slot {
    private ByteBuffer slice;
    private WritableByteChannel channel;
    private M marshaller;
    private boolean isReleased = false;

    OutputSlot(ByteBuffer slice, WritableByteChannel channel, M marshaller) {
        this.slice = slice;
        this.channel = channel;
        this.marshaller = marshaller;
    }

    /**
     * Appends a new record to this slot. Flushes to the data storage ifnecessary.
     * @param value
     * @throws IOException
     */
    public void append(T value) throws IOException {
        if (this.slice.remaining() < this.marshaller.getDataItemSize()) {
            flush();
        }
        assert this.slice.remaining() >= this.marshaller.getDataItemSize();
        byte[] bytes = this.marshaller.write(value);
        this.slice.put(bytes);
    }

    /**
     * Flushes the content of this slot to the data storage.
     * @throws IOException
     */
    public void flush() throws IOException {
    	CalculatorOfWorkingWithDisk.callFlush();
    	
        this.slice.flip();
        this.channel.write(this.slice);
        this.slice.clear();
    }

    public ByteBuffer getSlice() {
        return this.slice;
    }

    public boolean isReleased() {
        return this.isReleased;
    }

    public void setSlice(ByteBuffer slice) {
        this.slice = slice;
    }

    /**
     * Releases this slot and its buffers.
     */
    public void release() {
    	CalculatorOfWorkingWithDisk.callReleaseInOutputSlot();
    	
        this.isReleased = true;
        try {
            this.channel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
